﻿using GenshinLauncher;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace GenshinLuncher
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public string ConfigPath = "./config.ini";
        public string fps_config = "./fps_config.ini";

        public MainWindow()
        {
            InitializeComponent();
            string GPath = Win32API.INIGetStringValue(ConfigPath, "General", "GamePath", null);
            string UnlockFPS_Value = Win32API.INIGetStringValue(ConfigPath, "General", "UnlockFPS", null);
            //判断配置文件是否存在，如果不存在就创建file文件夹
            if (File.Exists(ConfigPath) == false)
            {
                //创建完成后释放，不然无法写入
                File.Create(ConfigPath).Dispose();
            }
            if (File.Exists(fps_config) == false)
            {
                File.Create(fps_config).Dispose();
            }
            GamePath.Text = GPath;
            if (UnlockFPS_Value == "True")
            {
                UnlockFPS.IsChecked = true;
            }
            else
            {
                UnlockFPS.IsChecked = false;
            }
            messagelist.Items.Clear();
            ListBoxAddLabel("初始化完成......");
        }

        //打开哔哩哔哩服
        private void OpenBilibili(object sender, RoutedEventArgs e)
        {
            messagelist.Items.Clear();
            ChangeConfig("14", "bilibili", "0", "哔哩哔哩服");
        }
        //打开官服
        private void OpenMihoyo(object sender, RoutedEventArgs e)
        {
            messagelist.Items.Clear();
            ChangeConfig("1", "mihoyo", "1", "官方服");
        }
        //选择游戏目录
        private void SelectGamePath(object sender, RoutedEventArgs e)
        {
            string GPath = "";
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
            if (folderBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                GPath = folderBrowser.SelectedPath;
            }

            //判断路径是否正确（检测是否存在YuanShen.exe）
            string path = GPath.Replace("\\", "/") + "/Genshin Impact Game/YuanShen.exe";
            if (File.Exists(path) == false)
            {
                ListBoxAddLabel("未检测到游戏程序！");
            }
            else
            {
                Win32API.INIWriteValue(fps_config, "Setting", "Path", GPath + "\\Genshin Impact Game\\YuanShen.exe");
                Win32API.INIWriteValue(fps_config, "Setting", "FPS", "144");
                //写入配置文件
                bool IsSuc = Win32API.INIWriteValue(ConfigPath, "General", "GamePath", GPath);
                if (!IsSuc)
                {
                    ListBoxAddLabel("配置文件写入失败！");
                }
                else
                {
                    GamePath.Text = GPath;
                }
            }
        }
        //修改游戏配置文件并启动游戏程序
        public void ChangeConfig(string channel, string cps, string sub_channel, string serviceName)
        {
            //从配置文件中获取游戏地址
            string GPath = Win32API.INIGetStringValue(ConfigPath, "General", "GamePath", null);
            if (GPath != null && GPath != "")
            {
                ListBoxAddLabel("正在切换到" + serviceName + ".....");
                GPath = GPath.Replace("\\", "/");
                string Game_ConfigPath = GPath + "/Genshin Impact Game/config.ini";
                string Launcher_ConfigPath = GPath + "/config.ini";
                if (File.Exists(Game_ConfigPath) == false)
                {
                    ListBoxAddLabel("配置文件不存在！");
                }
                //游戏配置文件
                bool Game_channelSuc = Win32API.INIWriteValue(Game_ConfigPath, "General", "channel", channel);
                bool Game_cpsSuc = Win32API.INIWriteValue(Game_ConfigPath, "General", "cps", cps);
                bool Game_sub_channelSuc = Win32API.INIWriteValue(Game_ConfigPath, "General", "sub_channel", sub_channel);
                //登陆器配置文件
                bool Launcher_channelSuc = Win32API.INIWriteValue(Launcher_ConfigPath, "launcher", "channel", channel);
                bool Launcher_cpsSuc = Win32API.INIWriteValue(Launcher_ConfigPath, "launcher", "cps", cps);
                bool Launcher_sub_channelSuc = Win32API.INIWriteValue(Launcher_ConfigPath, "launcher", "sub_channel", sub_channel);
                if (Game_channelSuc && Launcher_channelSuc && Game_cpsSuc && Launcher_cpsSuc && Game_sub_channelSuc && Launcher_sub_channelSuc)
                {
                    ListBoxAddLabel("切换成功，正在启动" + serviceName + "......");
                    //启动游戏程序
                    System.Threading.Thread thread = new System.Threading.Thread(() =>
                    {
                        //500ms后启动程序
                        System.Threading.Thread.Sleep(500);
                        Dispatcher.Invoke(new Action(() =>
                        {
                            string UnlockFPS_Value = Win32API.INIGetStringValue(ConfigPath, "General", "UnlockFPS", null);
                            string YSPath = GPath + "/Genshin Impact Game";
                            if (UnlockFPS_Value == "True")
                            {
                                if (File.Exists("./unlockfps.exe"))
                                {
                                    OpenEXE("unlockfps.exe", "./");
                                }
                                else
                                {
                                    ListBoxAddLabel("未检测到unlockfps.exe！");
                                    ListBoxAddLabel("直接启动游戏程序！");
                                    OpenEXE("YuanShen.exe", YSPath);
                                }
                            }
                            else
                            {
                                OpenEXE("YuanShen.exe", YSPath);
                            }
                            ListBoxAddLabel("游戏启动成功！");
                            System.Threading.Thread EXthread = new System.Threading.Thread(() =>
                            {
                                //500ms后程序最小化
                                System.Threading.Thread.Sleep(500);
                                Dispatcher.Invoke(new Action(() =>
                                {
                                    this.WindowState = WindowState.Minimized;
                                }));
                            });
                            EXthread.Start();

                        }));
                    });
                    thread.Start();
                }
            }
            else
            {
                ListBoxAddLabel("请选择游戏路径");
            }
        }
        //消息提示
        public void SendMessage(string msg)
        {
            System.Threading.Thread thread = new System.Threading.Thread(() =>
            {
                System.Windows.MessageBox.Show(msg, "提示", MessageBoxButton.OK, MessageBoxImage.None, MessageBoxResult.None, System.Windows.MessageBoxOptions.ServiceNotification);
            });
            thread.Start();
        }
        //解锁FPS选中事件
        private void UnlockFPS_Checked(object sender, RoutedEventArgs e)
        {
            //写入配置文件
            bool IsSuc = Win32API.INIWriteValue(ConfigPath, "General", "UnlockFPS", "True");
            if (!IsSuc)
            {
                ListBoxAddLabel("配置文件写入失败!");
            }
        }
        //解锁FPS取消事件
        private void UnlockFPS_Unchecked(object sender, RoutedEventArgs e)
        {
            //写入配置文件
            bool IsSuc = Win32API.INIWriteValue(ConfigPath, "General", "UnlockFPS", "False");
            if (!IsSuc)
            {
                ListBoxAddLabel("配置文件写入失败!");
            }
        }
        //ListBox添加文本
        private void ListBoxAddLabel(string content)
        {
            System.Windows.Controls.Label label = new System.Windows.Controls.Label();
            label.Content = content;
            messagelist.Items.Add(label);
        }
        //启动程序
        private void OpenEXE(string name, string path)
        {
            ShellExecute(IntPtr.Zero, new StringBuilder("Open"), new StringBuilder(name), new StringBuilder(""), new StringBuilder(path), 1);
        }
        [DllImport("shell32.dll")]
        public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);
    }
}
